package com.springboot.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
public class FileUploadController {

    private static final String UPLOAD_DIR = "fileData";

    @PostMapping("/upload/mp3")
    public ResponseEntity<Result> uploadMp3File(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>(new Result(false, "文件为空"), HttpStatus.BAD_REQUEST);
        }

        try {
            // 检查文件是否为MP3格式（简单检查文件名后缀）
            if (!file.getOriginalFilename().toLowerCase().endsWith(".mp3")) {
                return new ResponseEntity<>(new Result(false, "文件类型必须为MP3"), HttpStatus.BAD_REQUEST);
            }

            // 确保上传目录存在
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 构建文件保存路径
            Path filePath = uploadPath.resolve(file.getOriginalFilename());

            // 保存文件到指定路径
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            return new ResponseEntity<>(new Result(true, "文件上传成功", filePath.toString()), HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(new Result(false, "文件写入失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(new Result(false, "上传失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    /**
     * 下载上传的MP3文件
     *
     * @param fileName 要下载的MP3文件名
     * @return ResponseEntity<Resource> 返回包含文件资源的响应实体
     * 如果文件不存在返回404 NOT_FOUND
     * 如果文件不是MP3格式返回400 BAD_REQUEST
     * 如果发生MalformedURLException或IOException返回500 INTERNAL_SERVER_ERROR
     */
    @GetMapping("/download/mp3/{fileName}")
    public ResponseEntity<Resource> downloadMp3File(@PathVariable String fileName) {
        try {
            // 构建项目同级目录的绝对路径
            Path projectPath = Paths.get("").toAbsolutePath();
            Path uploadPath = projectPath.getParent().resolve(UPLOAD_DIR);
            Path filePath = projectPath.resolve(UPLOAD_DIR).resolve(fileName);

            /**
             * 检查文件是否存在
             */
            if (!Files.exists(filePath)) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

            /**
             * 验证文件扩展名是否为.mp3
             */
            if (!fileName.toLowerCase().endsWith(".mp3")) {
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }

            /**
             * 创建UrlResource对象以提供文件下载
             */
            Resource resource = new UrlResource(filePath.toUri());

            /**
             * 构建HTTP响应头信息
             * 设置Content-Disposition为附件形式下载
             * 设置Content-Type为audio/mpeg
             */
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
            headers.add(HttpHeaders.CONTENT_TYPE, "audio/mpeg");

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(Files.size(filePath))
                    .body(resource);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    static class Result {
        private boolean success; // 是否成功
        private String message;  // 消息
        private Object data;     // 数据（可选）

        // 构造方法（成功响应）
        public Result(boolean success, String message) {
            this.success = success;
            this.message = message;
            this.data = null;
        }

        // 构造方法（带数据的成功响应）
        public Result(boolean success, String message, Object data) {
            this.success = success;
            this.message = message;
            this.data = data;
        }

        // Getter 和 Setter（省略，可根据需要添加）
        public boolean isSuccess() {
            return success;
        }

        public String getMessage() {
            return message;
        }

        public Object getData() {
            return data;
        }
    }
}